<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
      <el-form-item label="课本角色名称" prop="roleName">
        <el-input v-model="dataForm.roleName" placeholder="课本角色名称"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
      <el-form-item  size="mini" label="授权">
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="filterText">
        </el-input>

        <el-tree
          class="filter-tree"
          :data="bookData"
          node-key="id"
          show-checkbox
          :props="defaultProps"
          default-expand-all
          :filter-node-method="filterNode"
          ref="booksTree">
        </el-tree>            
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { treeDataTranslate } from '@/utils'
  export default {
     watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    data () {
      return {
        filterText: '',
        bookData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        visible: false,
        menuList: [],
        menuListTreeProps: {
          label: 'name',
          children: 'children'
        },
        dataForm: {
          id: 0,
          roleName: '',
          remark: ''
        },
        dataRule: {
          roleName: [
            { required: true, message: '角色名称不能为空', trigger: 'blur' }
          ]
        },
        tempKey: -666666 // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
      }
    },
    methods: {
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      getBookData(id){
        this.bookData = [];
        this.dataForm.roleName = '';
        this.dataForm.roleName = '';
        this.dataForm.id = id || 0;
        this.$http({
          url: this.$http.adornUrl('/sf/bookrole/getAllBook'),
          method: 'get',
        }).then(({data}) => {
          let allBookEditionList = data.allBookEditionList;
          let allStiffBookEditionList = data.allStiffBookEditionList;
          let expandEditionList = data.expandEditionList;
          let expandEditionStiffList = data.expandEditionStiffList;
          console.log(data);
          let level1 = {};
          level1['id'] = 0;
          level1['label'] = '软笔';
          level1['children'] = [];
          for(var i=0 ; i<allBookEditionList.length ; ++i){
            let level2 = {};
            let allBook = allBookEditionList[i].bookBasicInfoVoList;
            level2['id'] = allBookEditionList[i].id;
            level2['label'] = allBookEditionList[i].editionName;
            level2['children'] = [];
            for(var j=0 ; j<allBook.length ; ++j){
              let level3 = {};
              let book = allBook[j];
              level3['id'] = book.id;
              level3['label'] = book.grade;
              level3['booktype'] = 0;
              level2['children'].push(level3);
            }
            level1['children'].push(level2);
          }
          this.bookData.push(level1);
          level1 = {};
          level1['id'] = 1;
          level1['label'] = '硬笔';
          level1['children'] = [];
          for(var i=0 ; i<allStiffBookEditionList.length ; ++i){
            let level2 = {};
            let allBook = allStiffBookEditionList[i].bookBasicInfoVoList;
            level2['id'] = allStiffBookEditionList[i].id;
            level2['label'] = allStiffBookEditionList[i].editionName;
            level2['children'] = [];
            for(var j=0 ; j<allBook.length ; ++j){
              let level3 = {};
              let book = allBook[j];
              level3['id'] = book.id;
              level3['label'] = book.grade;
              level3['booktype'] = 1;
              level2['children'].push(level3);
            }
            level1['children'].push(level2);
          }
          this.bookData.push(level1);
          level1 = {};
          level1['id'] = 2;
          level1['label'] = '软笔扩展';
          level1['children'] = [];
          for(var i=0 ; i<expandEditionList.length ; ++i){
            let level2 = {};
            level2['id'] = expandEditionList[i].id;
            if(expandEditionList[i].expandEditionType == 0)
              level2['label'] = '碑帖欣赏';
            else if(expandEditionList[i].expandEditionType == 1)
              level2['label'] = '国学经典';
            else if(expandEditionList[i].expandEditionType == 2)
              level2['label'] = '书法知识';
            level2['booktype'] = 2;
            level1['children'].push(level2);
          }
          this.bookData.push(level1);
          level1 = {};
          level1['id'] = 3;
          level1['label'] = '硬笔扩展';
          level1['children'] = [];
          for(var i=0 ; i<expandEditionStiffList.length ; ++i){
            let level2 = {};
            level2['id'] = expandEditionStiffList[i].id;
            if(expandEditionStiffList[i].expandEditionType == 0)
              level2['label'] = '碑帖欣赏';
            else if(expandEditionStiffList[i].expandEditionType == 1)
              level2['label'] = '国学经典';
            else if(expandEditionStiffList[i].expandEditionType == 2)
              level2['label'] = '书法知识';
            level2['booktype'] = 3;
            level1['children'].push(level2);
          }
          this.bookData.push(level1);
        }).then(()=>{
          this.visible = true;
          this.$nextTick(() => {
            this.$refs.booksTree.setCheckedKeys([]);
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sf/bookright/getRoleRightsById/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              this.dataForm.roleName = data.bookRole.roleName;
              this.dataForm.remark = data.bookRole.remark;
              let checkedKeys = [];
              checkedKeys = data.bookIds;
              for (var index in data.stiffBookIds) {
                checkedKeys.push(data.stiffBookIds[index]);
              }
              for (var index in data.bookExpandIds) {
                checkedKeys.push(data.bookExpandIds[index]);
              }
              for (var index in data.stiffBookExpandIds) {
                checkedKeys.push(data.stiffBookExpandIds[index]);
              }
              this.$refs.booksTree.setCheckedKeys(checkedKeys);
            })
          }
        });
      },
      // 表单提交
      dataFormSubmit () {
        let selectNodes = this.$refs.booksTree.getCheckedNodes(true,false);
        //软笔、硬笔书id数组
        let bookIds = [];
        let stiffBookIds = [];
        let bookExpandIds = [];
        let stiffBookExpandIds = [];

        for(var i=0 ; i<selectNodes.length ; ++i){
          if(selectNodes[i].booktype === 0) bookIds.push(selectNodes[i].id);
          else if(selectNodes[i].booktype === 1)  stiffBookIds.push(selectNodes[i].id);
          else if(selectNodes[i].booktype === 2)  bookExpandIds.push(selectNodes[i].id);
          else if(selectNodes[i].booktype === 3)  stiffBookExpandIds.push(selectNodes[i].id);
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/sf/bookrole/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'roleName': this.dataForm.roleName,
                'remark': this.dataForm.remark,
                'bookIds': bookIds,
                'stiffBookIds': stiffBookIds,
                'bookExpandIds' : bookExpandIds,
                'stiffBookExpandIds' : stiffBookExpandIds,
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        });
      }
    }
  }
</script>
